<template>
  <div style="width: 40%; margin: 0 auto">
    <div style="width:100%;position: fixed;top: 0;left: 0;z-index: -10;bottom: 0;right: 0; background-color: #f2f6fc"></div>
    <div class="title" style="font-size:23px;margin-bottom: 30px;padding-top:40px">注册在线聊天室</div>
    <!-- 用户注册 -->
    <div class="register">
      <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <!-- 头像2.0 -->
        <el-form-item label="头像">
          <div class="item_bock head_p">
            <div class="head_img">
              <img :src="ruleForm.avatar"/>
            </div>
              <div class="setting_right" @click.stop="uploadHeadImg">
                <el-button type="primary" plain>上传头像</el-button>
              </div>
              <input type="file" accept="image/*" @change="handleFile" class="hiddenInput" />
            </div>
        </el-form-item>
        <!-- 账号密码 ，用户名-->
        <el-form-item label="账户" prop="uid">
          <el-input v-model="ruleForm.uid"></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="ruleForm.userName"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="pass">
          <el-input type="password" v-model="ruleForm.pass" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass">
          <el-input type="password" v-model="ruleForm.checkPass" autocomplete="off"></el-input>
        </el-form-item>
        <!-- 性别 备选项-->
        <el-form-item label="性别" prop>
          <el-radio v-model="ruleForm.gender" @change="male" label="1">男</el-radio>
          <el-radio v-model="ruleForm.gender" @change="female" label="2">女</el-radio>
        </el-form-item>
        <!-- 生日 -->
        <el-form-item label="生日" prop>
          <div class="block">
            <el-date-picker v-model="ruleForm.birth" type="date" placeholder="选择日期">
            </el-date-picker>
          </div>
        </el-form-item>
        <!-- 简介 -->
      <el-form-item label="个性签名" prop="content">
          <el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="ruleForm.content">
          </el-input>
        </el-form-item>
        <!-- 验证码 -->
        <el-form-item prop="code">
          <el-input type="text" v-model="ruleForm.code" placeholder="- - - -" >
            <template slot="prepend" >验证码</template>
            <template slot="append">
              <div class="login-code" @click="refreshCode">
                <identify-code :identifyCode="identifyCode"></identify-code>
              </div>
            </template>
          </el-input>
        </el-form-item>
        <!-- 提交，重置 -->
        <el-form-item>
          <el-button type="primary" :load="ruleForm.btnLoading" @click="submitForm('ruleForm')">提交</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
        <!-- 登录 -->
        <el-form-item>
          <router-link to='./login'>
            <div class="register">已有帐户?
              <el-button type="text"> 前往登录 </el-button>
            </div>
          </router-link>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
  import moment from 'moment'
import IdentifyCode from './components/IdentifyCode'
export default {
  name: 'Register',
  components :{
    IdentifyCode
  },
  data() {
    var checkUid = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('注册账号不能为空'))
      }
      var reg = /^[0-9a-zA-Z]+$/
      if (!reg.test(value)) {

        alert("你输入的字符不是数字或者字母")
        return callback(new Error('你输入的字符不是数字或者字母'))
      }
      var that = this
      this.$http(this.$api.checkUid, { uid: this.ruleForm.uid }).then(res => {
        console.log(res)
        if (res.data === false) {
          console.log("注册失败");
          that.$message.error('注册失败，账户已存在')
        } else {
          console.log("该账户可以注册");
          that.$message.success('该账户可以注册')
        }
      }, fail => {
        that.$message.error('错误'+fail)
        // ceshi
      })
      setTimeout(() => {
        {
          callback()
        }
        // function checkUid(obj) {
        // alert(obj.value); //测试获取输入的id
        // 应用路径
        // var contextPath;
        // var contextPath = [[${#request.getContextPath()}]];
        //异步实现
        // $ajax({

        //   url: contextPath + 'userinfo/CheckUid',
        //   data: { "uid": obj.value },
        //   method: "post",
        //   //如果验证成功，执行这个回调函数
        //   success: function(data) {
        //     alert(data);
        //     if (data == "1") { //用户已经存在
        //       that.$message.error('账号已经存在，请重新注册');
        //       return
        //     } else {
        //       //用户名合法
        //       // callback(new Error('账号可以注册'));
        //       that.$message.success('账号可以注册')
        //       return;
        //     }
        //   }
        // })
        // }

      }, 1000)
    };
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (this.ruleForm.checkPass !== '') {
          this.$refs.ruleForm.validateField('checkPass');
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.ruleForm.pass) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      identifyCodes: '1234567890abcdefjhijklinopqrsduvwxyz',
      identifyCode: '',

      ruleForm: {
        uid: '',
        userName: '',
        pass: '',
        checkPass: '',
        //性别1,2,3分别代表男，女，空
        gender: 3,
        content: '',
        birth: '',
        avatar: 'https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=2992840297,621717109&fm=26&gp=0.jpg',
        avator: ' ',
        code: "",
        btnLoading: false
      },
      rules: {
        pass: [
          { validator: validatePass, trigger: 'blur' } //光标离开就校验
        ],
        checkPass: [
          { validator: validatePass2, trigger: 'blur' }
        ],
        uid: [
          { validator: checkUid, trigger: 'blur' }
        ],
        code: [{ required: true, message: "请输入验证码", trigger: "blur" }]
      },
      content: [
          { required: true, message: '请填写活动形式', trigger: 'blur' }
        ]
    };
  },
  methods: {
    //格式化时间
    format(time, format) {
      var t = new Date(time);
      var tf = function(i) { return (i < 10 ? '0' : '') + i };
      return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function(a) {
        switch (a) {
          case 'yyyy':
            return tf(t.getFullYear());
            break;
          case 'MM':
            return tf(t.getMonth() + 1);
            break;
          case 'mm':
            return tf(t.getMinutes());
            break;
          case 'dd':
            return tf(t.getDate());
            break;
          case 'HH':
            return tf(t.getHours());
            break;
          case 'ss':
            return tf(t.getSeconds());
            break;
        }
      })
    },
    refreshCode() {
      this.identifyCode = ''
      this.makeCode(this.identifyCodes, 4)
    },
    makeCode(o, l) {
      for (let i = 0; i < l; i++) {
        this.identifyCode += this.identifyCodes[this.randomNum(0, this.identifyCodes.length)]
      }
    },
    randomNum(min, max) {
      return Math.floor(Math.random() * (max - min) + min)
    },

    // 打开图片上传
    uploadHeadImg: function() {
      // 获取文档中 class=”hiddenInput”
      this.$el.querySelector('.hiddenInput').click()
    },
    // 将头像显示
    handleFile: function(e) {
      let $target = e.target || e.srcElement
      // 表示取第一张图
      let file = $target.files[0]
      var reader = new FileReader()
      reader.onload = (data) => {
        let res = data.target || data.srcElement
        this.ruleForm.avatar = res.result
      }
      // .FileReader对象的readAsDataURL方法可以将读取到的文件编码成Data URL
      reader.readAsDataURL(file)
      return this.ruleForm.avatar
    },
    //gender
    male() {
      this.ruleForm.gender == 1;
      return this.ruleForm.gender;
    },
    female() {
      this.ruleForm.gender == 2;
      return this.ruleForm.gender;
    },
    submitForm(formName) {
      //验证码
      if (this.ruleForm.code.toLowerCase() !== this.identifyCode.toLowerCase()) {
        this.$message.error('请填写正确验证码')
        this.refreshCode()
        return
      }
      this.ruleForm.birth = this.$options.methods.format(this.ruleForm.birth, 'yyyy/MM/dd');
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log('submit!');
          console.log(this.ruleForm.avatar);

          var that = this;
          // this.ruleForm.btnLoading = true;
          this.$http(this.$api.register, {
            uid: this.ruleForm.uid,
            userName: this.ruleForm.userName,
            password: this.ruleForm.pass,
            content:this.ruleForm.content,
            birth: this.ruleForm.birth,
            avatar: this.ruleForm.avatar,
            gender: this.ruleForm.gender,
            avator: this.ruleForm.avator,

          }).then(res => {
            if (res.data === false) {
              console.log("注册失败");
              that.$message.error('注册失败');
            } else {
              console.log(res);
              console.log("注册成功");
              that.$message.success('注册成功');
              that.$router.push('/login')
            }
            // that.btnLoading = false;
          }, fail => {
            that.$message.error("错误: " + fail);
            // that.btnLoading = false;
          })

        } else {
          console.log('error submit!!');
          return false;
        }
      });

    },
    resetForm(formName) { //传入的参数是ruleForm的
      this.$refs[formName].resetFields();
    }
  },
  mounted() {
    // 初始化验证码
    this.identifyCode = ''
    this.makeCode(this.identifyCodes, 4)
  }
  // beforeCreate() {
  //   this.windowHeight = window.innerHeight
  // }
}

</script>
<style scoped>
  .el-input__inner{
    line-height: 45px;
  }
.item_bock {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 94px;
  width: 240px;
  padding: 0px 24px 0px 38px;
  border-bottom: 1px solid #f7f7f7;
  background: #fff;
  border-radius: 5px;
}

.head_p {
  height: 132px;
}

.head_img {
  height: 90px;
}

.head_img img {
  width: 90px;
  height: 90px;
  border-radius: 50px
}

.setting_right {
  display: flex;
  height: 37px;
  justify-content: flex-end;
  align-items: center;
}

.hiddenInput {
  display: none;
}

.caption {
  color: #8F8F8F;
  font-size: 26px;
  height: 37px;
}

</style>
